<?php

namespace app\queue\stomp;

use app\queue\BaseConsumer;
use common\model\TaskModel;
use common\service\CommonService;

class TaskStepCategoryPlanTimeFixData extends BaseConsumer
{
    // 要消费的队列名
    public $queue = 'task_step_category_plan_time_fix_data';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    public function doConsume($data)
    {
        if (empty($data['fixData'])) {
            return;
        }

        $fixStepCategoryData = $data['fixData'];
        $stepMaxId = model(TaskModel::class)->field('max(id) as id')
            ->where(['entity_id' => ['IN', array_column($fixStepCategoryData, 'entity_id')], 'step_type' => 'step'])
            ->where($data['filter'])
            ->group('entity_id,step_category_id')
            ->column('id');

        $stepPlanTimeMap = model(TaskModel::class)->field('id,step_category_id,plan_start_time,plan_end_time,entity_id')
            ->where(['id' => ['IN', $stepMaxId], 'step_type' => 'step'])
            ->select();
        $updateData = [];
        $stepPlanTimeMap = array_group_by($stepPlanTimeMap, 'entity_id');
        foreach ($fixStepCategoryData as $item) {
            if (empty($stepPlanTimeMap[$item['entity_id']])) {
                continue;
            }
            $stepCategoryMap = array_column($stepPlanTimeMap[$item['entity_id']], null, 'step_category_id');
            if (empty($stepCategoryMap[$item['step_category_id']]['plan_start_time']) && empty($stepCategoryMap[$item['step_category_id']]['plan_end_time'])) {
                continue;
            }
            $item['plan_start_time'] = $stepCategoryMap[$item['step_category_id']]['plan_start_time'];
            $item['plan_end_time'] = $stepCategoryMap[$item['step_category_id']]['plan_end_time'];

            $planStartTime = date('Y-m-d H:i:s', $item['plan_start_time']);
            $planEndTime = date('Y-m-d H:i:s', $item['plan_end_time']);
            $updateData[] = [
                'id' => $item['id'],
                'plan_end_time' => $planEndTime,
                'plan_start_time' => $planStartTime
            ];
        }
        try {
            CommonService::instance('task')->commonBatchUpdate($updateData, '', false);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}